<?php

class Model_Mapper_Alerts {
	
	protected $_dbTable;
	private static $instance;
	
	public static function newInstance() {
		if (! self::$instance instanceof self) {
			self::$instance = new self ();
		}
		return self::$instance;
	}
	
	public function setDbTable($dbTable) {
		if (is_string ( $dbTable )) {
			$dbTable = new $dbTable ();
		}
		if (! $dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception ( 'Invalid table data gateway provided' );
		}
		$this->_dbTable = $dbTable;
		return $this;
	}
	
	public function getDbTable() {
		if (null === $this->_dbTable) {
			$this->setDbTable ( 'Model_Table_Alerts' );
		}
		return $this->_dbTable;
	}
	
	public function save(Model_Alerts $alerts) {
		$data = array ('email' => $alerts->getEmail (), 'user_id' => $alerts->getUser_id (), 'search' => $alerts->getSearch (), 'secret' => $alerts->getSecret (), 'active' => $alerts->getActive (), 'type' => $alerts->getType () );
		$key = $this->getDbTable ()->getPrimaryKey ();
		$method = 'get' . ucfirst ( $key );
		$val = $categories->$method ();
		if ($val == null) {
			unset ( $data [$key] );
			$this->getDbTable ()->insert ( $data );
		} else {
			$this->getDbTable ()->update ( $data, array ($key . ' = ?' => $val ) );
		}
	}
	
	private function extend($args) {
		$items = array ();
		foreach ( $args as $arg ) {
			$arg = $arg->toArray ();
			$item = new Model_Alerts ( $arg );
			$items [] = $item;
		}
		return $items;
	}
	
	public function lastInsertID() {
		return $this->getDbTable ()->getAdapter ()->lastInsertId ();
	}
	
	public function beginTransaction() {
		$this->getDbTable ()->getAdapter ()->beginTransaction ();
	}
	
	public function commit() {
		$this->getDbTable ()->getAdapter ()->commit ();
	}
	
	public function rollBack() {
		$this->getDbTable ()->getAdapter ()->rollBack ();
	}
	
	public function getAll($enabled = false) {
		$table = $this->getDbTable ();
		$select = $table->select ();
		$select->from ( $this->getDbTable () );
		if ($enabled) {
			$select->where ( 'enabled=?', 1 );
		}
		return $this->extend ( $table->fetchAll ( $select ) );
	}
	
	public function getByID($id) {
		if ($id == '') {
			throw new Exception ( 'Invalid ID Provided.' );
		}
		$table = $this->getDbTable ();
		$select = $table->select ();
		$select->where ( $this->getDbTable ()->getPrimaryKey () . '=?', $id );
		$select->from ( $this->getDbTable () );
		$result = $this->extend ( $table->fetchAll ( $select ) );
		return $result [0];
	}

}